package com.minisoft.utils.thread;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Console;

import java.util.concurrent.CompletableFuture;

/**
 * @author JueSu
 * @description: TODO
 * @date 2022/8/30 15:44
 */
public class CompletableFutureTest {
    private static void completableFuture10() throws Exception {
        CompletableFuture<String> completableFuture1 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "hello world1";
        });
        CompletableFuture<String> completableFuture2 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "hello world2";
        });
        Console.log(DateUtil.now());
        CompletableFuture<Void> allOf = CompletableFuture.allOf(completableFuture1, completableFuture2);
        allOf.get();//等所有任务完成
        Console.log(DateUtil.now());
        System.out.println(completableFuture2.get());
        System.out.println(completableFuture1.get());
    }
    private static void completableFuture11() throws Exception {
        CompletableFuture<Void> completableFuture1 = CompletableFuture.runAsync(() -> {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        CompletableFuture<Void> completableFuture2 = CompletableFuture.runAsync(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        Console.log(DateUtil.now());
        CompletableFuture<Void> allOf = CompletableFuture.allOf(completableFuture1, completableFuture2);
        allOf.get();//等所有任务完成
        Console.log(DateUtil.now());
        System.out.println(completableFuture2.get());
        System.out.println(completableFuture1.get());
    }
    public static void main(String[] args) throws Exception {
        completableFuture10();
        completableFuture11();
        System.in.read();
    }
}
